﻿//using Microsoft.EntityFrameworkCore;
//using Microsoft.EntityFrameworkCore.Storage;
//using Microsoft.Extensions.Logging;
//using Sgr.Domain.Uow;
//using System;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Data;
//using System.Data.Common;
//using System.Linq;
//using System.Text;
//using System.Threading;
//using System.Threading.Tasks;

//namespace Sgr.EntityFrameworkCore
//{
//    /// <summary>
//    /// EF Core事务包装器，实现IUnitOfWorkTransaction接口
//    /// </summary>
//    public class EfCoreTransaction<TModule, TDbContext> : IUnitOfWorkTransaction, IUnitOfWorkEventHandling
//        where TDbContext : DbContext
//        where TModule : class
//    {
//        private readonly IDbContextTransaction _transaction;
//        private readonly EfCoreUnitOfWork<TModule, TDbContext> _unitOfWork;
//        private readonly ILogger<EfCoreTransaction<TModule, TDbContext>> _logger;
//        private readonly EfCoreTransaction<TModule, TDbContext>? _outerTransaction;
//        private readonly IsolationLevel _isolationLevel; // 添加字段记录隔离级别

//        /// <summary>
//        /// 数据库事务提交成功后的处理事件
//        /// </summary>
//        protected ConcurrentBag<Func<Task>> _completedHandlers;

//        protected bool _isCompleted;
//        private bool _disposed;

//        public EfCoreTransaction(
//            EfCoreUnitOfWork<TModule, TDbContext> unitOfWork,
//            IDbContextTransaction transaction,
//            IsolationLevel isolationLevel,
//            ILogger<EfCoreTransaction<TModule, TDbContext>> logger,
//            EfCoreTransaction<TModule, TDbContext>? outerTransaction = null)
//        {
//            _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
//            _transaction = transaction ?? throw new ArgumentNullException(nameof(transaction));
//            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
//            _isolationLevel = isolationLevel;
//            _outerTransaction = outerTransaction;

//            _completedHandlers = new ConcurrentBag<Func<Task>>();
//            _isCompleted = false;

//            if (_outerTransaction != null)
//            {
//                _logger.LogDebug(
//                    "Creating nested transaction {TransactionId} under outer transaction {OuterTransactionId}",
//                    TransactionId,
//                    _outerTransaction.TransactionId);
//            }
//        }

//        /// <summary>
//        /// 获取事务对象
//        /// </summary>
//        public IDbContextTransaction DbTransaction => _transaction;

//        /// <summary>
//        /// 当前事务的隔离级别
//        /// </summary>
//        public IsolationLevel IsolationLevel => _isolationLevel;

//        /// <summary>
//        /// 获取外层事务包装器
//        /// </summary>
//        public EfCoreTransaction<TModule, TDbContext>? OuterTransaction => _outerTransaction;

//        #region IUnitOfWorkEventHandling

//        /// <summary>
//        /// 添加事务提交成功后的处理事件
//        /// </summary>
//        /// <param name="handler"></param>
//        public virtual void AddTransactionCompletedHandler(Func<Task> handler)
//        {
//            ArgumentNullException.ThrowIfNull(handler);
//            ThrowIfDisposed();
//            ThrowIfCompleted();

//            _completedHandlers.Add(handler);
//        }

//        protected virtual async Task OnCompletedAsync()
//        {
//            var handlers = _completedHandlers.ToList();

//            foreach (var handler in handlers)
//            {
//                try
//                {
//                    await handler.Invoke().ConfigureAwait(false);
//                }
//                catch (Exception ex)
//                {
//                    _logger.LogError(ex, "Error executing transaction completed handler for transaction {TransactionId}",
//                        TransactionId);
//                }
//            }
//        }

//        #endregion IUnitOfWorkEventHandling

//        #region IUnitOfWorkTransaction

//        /// <summary>
//        /// 事务ID
//        /// </summary>
//        public Guid TransactionId => _transaction.TransactionId;

//        /// <summary>
//        /// 是否为活动事务
//        /// </summary>
//        public bool IsActive => !_isCompleted && !_disposed;

//        /// <summary>
//        /// 提交事务
//        /// </summary>
//        /// <param name="cancellationToken"></param>
//        /// <returns></returns>
//        public async Task CommitAsync(CancellationToken cancellationToken = default)
//        {
//            ThrowIfDisposed();
//            ThrowIfCompleted();

//            try
//            {
//                // 保存更改
//                await _unitOfWork.SaveEntitiesAsync(cancellationToken);

//                // 提交事务
//                await _transaction.CommitAsync(cancellationToken);

//                // 执行完成事件处理程序
//                await OnCompletedAsync();

//                // 通知工作单元事务已完成
//                await _unitOfWork.OnTransactionCompletedAsync(this, true, cancellationToken);
//            }
//            catch (Exception ex)
//            {
//                _logger.LogError(ex, "Error committing transaction {TransactionId}. Rolling back...",
//                    TransactionId);

//                // 如果提交失败，尝试回滚
//                if (!_isCompleted)
//                    await RollbackAsync(cancellationToken);

//                throw;
//            }
//            finally
//            {
//                _isCompleted = true;
//            }
//        }

//        public async Task RollbackAsync(CancellationToken cancellationToken = default)
//        {
//            ThrowIfDisposed();

//            if (_isCompleted)
//            {
//                _logger.LogDebug("Transaction {TransactionId} is already completed, skipping rollback",
//                    TransactionId);
//                return;
//            }

//            try
//            {
//                await _transaction.RollbackAsync(cancellationToken);

//                // 如果是最外层事务，才清理 ChangeTracker
//                if (_outerTransaction == null)
//                {
//                    // 清理 DbContext 状态
//                    _unitOfWork.DbContext.ChangeTracker.Clear();
//                }

//                // 通知工作单元事务已回滚
//                await _unitOfWork.OnTransactionCompletedAsync(this, false, cancellationToken);
//            }
//            catch (Exception ex)
//            {
//                _logger.LogError(ex, "Error rolling back transaction {TransactionId}", TransactionId);
//                throw;
//            }
//            finally
//            {
//                _isCompleted = true;
//            }
//        }

//        #endregion IUnitOfWorkTransaction

//        #region IDisposable

//        /// <summary>
//        /// 释放事务资源
//        /// </summary>
//        public void Dispose()
//        {
//            Dispose(true);
//            GC.SuppressFinalize(this);
//        }

//        /// <summary>
//        /// 释放资源的实际实现
//        /// </summary>
//        /// <param name="disposing">是否释放托管资源</param>
//        protected virtual void Dispose(bool disposing)
//        {
//            if (!_disposed)
//            {
//                if (disposing)
//                {
//                    try
//                    {
//                        if (!_isCompleted)
//                        {
//                            _logger.LogWarning("Disposing uncommitted transaction {TransactionId}, rolling back...",
//                                TransactionId);
//                            _transaction.Rollback();
//                        }
//                        _transaction.Dispose();
//                        _logger.LogDebug("Successfully disposed transaction {TransactionId}", TransactionId);
//                    }
//                    catch (Exception ex)
//                    {
//                        _logger.LogError(ex, "Error disposing transaction {TransactionId}", TransactionId);
//                    }
//                }

//                _disposed = true;
//            }
//        }

//        public async ValueTask DisposeAsync()
//        {
//            if (!_disposed)
//            {
//                try
//                {
//                    if (!_isCompleted)
//                    {
//                        _logger.LogWarning("Async disposing uncommitted transaction {TransactionId}, rolling back...",
//                            TransactionId);
//                        await _transaction.RollbackAsync();
//                    }
//                    await _transaction.DisposeAsync();
//                    _logger.LogDebug("Successfully async disposed transaction {TransactionId}", TransactionId);
//                }
//                catch (Exception ex)
//                {
//                    _logger.LogError(ex, "Error async disposing transaction {TransactionId}", TransactionId);
//                }

//                _disposed = true;
//            }

//            GC.SuppressFinalize(this);
//        }

//        protected void ThrowIfDisposed()
//        {
//            ObjectDisposedException.ThrowIf(_disposed, GetType().Name);
//        }

//        protected void ThrowIfCompleted()
//        {
//            if (_isCompleted)
//            {
//                _logger.LogWarning("Attempted to operate on completed transaction {TransactionId}", TransactionId);
//                throw new InvalidOperationException($"Transaction {TransactionId} has already been completed.");
//            }
//        }

//        #endregion IDisposable
//    }
//}